package com.sinoglobal.shakeprize.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

/**
 * @author qiwx
 * @createdate 2014-6-6 下午3:47:21
 * @Description: 设备状态和参数的一些公用方法 ，分辨率，密度，联网等
 */
public class EquipmentUtil {
	public static boolean NO_NETWORK;
	private static Context mContext;
	private static EquipmentUtil instance;
	private static String CHANNEL_NAME; // 渠道名
	private static final String CHANNEL_KEY = "UMENG_CHANNEL";
	private static final String PHONE003 = "phone003";
	public static final int WINDOW_WIDTH = 1;
	public static final int WINDOW_HEIGHT = 2;
	public static String sUniquelyCode;// imei号

	private EquipmentUtil(Context context) {
		mContext = context;
	}

	public static synchronized EquipmentUtil getInstance(Context context) {
		if (instance == null) {
			instance = new EquipmentUtil(context);
			mContext = context;
		}
		return instance;
	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-6-10 下午2:28:04
	 * @Description:获得应用的当前版本号与版本名称，包名
	 * @type
	 * @return
	 * @throws Exception
	 */

	public static Map<String, Object> getVersionCode(Context context) {
		// 获取packagemanager的实例
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo;
		Map<String, Object> map = new HashMap<String, Object>();
		int VersionCode = 0;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(),
					0);
			map.put("VersionCode", Integer.valueOf(packInfo.versionCode));
			map.put("VersionName", packInfo.versionName);
			map.put("PackageName", packInfo.packageName);

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return map;
	}

	public static String getpackageName(Context context) {
		// 获取packagemanager的实例
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo;
		// /Map<String,Object> map=new HashMap<String,Object>();
		String packageName = "";
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(),
					0);
			/*
			 * map.put("VersionCode",Integer.valueOf(packInfo.versionCode));
			 * map.put("VersionName",packInfo.versionName);
			 * map.put("PackageName",packInfo.packageName);
			 */
			packageName = packInfo.packageName;

		} catch (NameNotFoundException e) {
			//Auto-generated catch block
			packageName = "";
			e.printStackTrace();
		}
		return packageName;
	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-6-10 下午2:42:15
	 * @Description:安装apk文件
	 * @type
	 * @return
	 * @throws Exception
	 */
	public static void installApk(File file, Context context) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");// 编者按：此处Android应为android，否则造成安装不了
		context.startActivity(intent);
	}

	public static Intent installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");// 编者按：此处Android应为android，否则造成安装不了
		return intent;
	}

	/**
	 * 
	 * @author czz
	 * @createdate 2014-2-27 下午3:05:39
	 * @Description: (修改文件权限 apk文件权限由-rw------- 变为-rw----r--，可以正常启动。)
	 * @param fileName
	 * @return
	 * 
	 */

	public static String exec(String fileName) {
		String[] args = { "chmod", "604", fileName };
		String result = "";
		ProcessBuilder processBuilder = new ProcessBuilder(args);
		Process process = null;
		InputStream errIs = null;
		InputStream inIs = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int read = -1;
			process = processBuilder.start();
			errIs = process.getErrorStream();
			while ((read = errIs.read()) != -1) {
				baos.write(read);
			}
			baos.write('n');
			inIs = process.getInputStream();
			while ((read = inIs.read()) != -1) {
				baos.write(read);
			}
			byte[] data = baos.toByteArray();
			result = new String(data);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (errIs != null) {
					errIs.close();
				}
				if (inIs != null) {
					inIs.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (process != null) {
				process.destroy();
			}
		}
		System.out.println(result);
		return result;
	}

	// 判断是否有sd卡
	public static boolean hasSDCard() {
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {
			return false;
		}
		return true;
	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-6-4 下午3:38:09
	 * @Description:获得目录，此方法比较灵活，根据不同需求创建所需要的目录
	 * @return
	 * @throws Exception
	 */
	public static String getRootFilePath() {
		if (hasSDCard()) {
			// sd卡 路径 /storage/sdcard0
			return Environment.getExternalStorageDirectory().getAbsolutePath()
					+ "/";// filePath:/sdcard/
		} else {
			// data 路径 /data
			return Environment.getDataDirectory().getAbsolutePath() + "/data/"; // filePath:
																				// /data/data/
		}
	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-6-4 下午3:37:05
	 * @Description:根据情况获得手机系统缓存目录
	 * @return
	 * @throws Exception
	 */
	public String getCachePath() {
		ItktLog.i(Environment.getExternalStorageDirectory().getPath());
		ItktLog.i(Environment.getDataDirectory().getPath());
		if (hasSDCard()) {
			// /storage/sdcard0/Android/data/packageName/cache
			// return Environment.getExternalStorageDirectory().getPath();

			return mContext.getExternalCacheDir().getPath();
		} else {
			// /data/data/packageName/cache
			// return mContext.getExternalCacheDir().getPath();
			return Environment.getDataDirectory().getPath();
		}
	}

	public static boolean checkNetState(Context context) {
		boolean netstate = false;
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						netstate = true;
						break;
					}
				}
			}
		}
		return netstate;
	}

	/**
	 * @author ty
	 * @createdate 2012-8-17 上午10:38:48
	 * @Description: 获取渠道名
	 * @param ctx
	 * @return
	 */
	public String getChanel(Context ctx) {
		if (TextUtils.isEmpty(CHANNEL_NAME)) {
			try {
				ApplicationInfo ai = ctx.getPackageManager()
						.getApplicationInfo(ctx.getPackageName(),
								PackageManager.GET_META_DATA);
				Object value = ai.metaData.get(CHANNEL_KEY);
				if (value != null) {
					CHANNEL_NAME = value.toString();
				} else {
					CHANNEL_NAME = "000000";
				}
			} catch (Exception e) {
			}
		}
		return CHANNEL_NAME;
	}

	/**
	 * 获取网络连接NetworkInfo对象
	 * 
	 * @param context
	 * @return
	 */
	public static NetworkInfo getNetworkInfo(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo = cm.getActiveNetworkInfo();
		return netinfo;
	}

	/**
	 * 网络类型
	 * 
	 * @param context
	 */
	public static void getNetWorkInfoType(Context context) {
		NetworkInfo networkinfo = getNetworkInfo(context);
		if (networkinfo != null)
			NO_NETWORK = false;
		else
			NO_NETWORK = true;
	}

	/**
	 * 根据手机的dp值 转换成px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率px(像素) 转换成dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 获得imei
	 * 
	 * @param context
	 * @return
	 */
	public String getUniquely(Context context) {
		if (TextUtils.isEmpty(sUniquelyCode)) {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			sUniquelyCode = tm.getDeviceId();
			if (TextUtils.isEmpty(sUniquelyCode)) {
				WifiManager wm = (WifiManager) context
						.getSystemService(Context.WIFI_SERVICE);
				sUniquelyCode = wm.getConnectionInfo().getMacAddress();
			}

			if (TextUtils.isEmpty(sUniquelyCode)) {
				sUniquelyCode = getUniquelyCodeFromMacAddress(getLocalMacAddress());
			}
		}
		return sUniquelyCode;
	}

	private String getUniquelyCodeFromMacAddress(String macAddress) {
		return macAddress.replaceAll(":", "");
	}

	private String getLocalMacAddress() {
		String macAddr = null;
		char[] buf = new char[1024];
		InputStreamReader isr = null;

		try {
			Process pp = Runtime.getRuntime().exec("busybox ifconfig eth0");
			isr = new InputStreamReader(pp.getInputStream());
			isr.read(buf);
			macAddr = new String(buf);
			int start = macAddr.indexOf("HWaddr") + 7;
			int end = start + 18;
			macAddr = macAddr.substring(start, end);
		} catch (Exception e) {
			macAddr = "Read Exception";
		}
		return macAddr;
	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-6-11 上午11:03:34
	 * @Description:获取手机大小，宽度与高度
	 * @type flag=1时代表宽度，flag=2时代表高度
	 * @throws Exception
	 */
	public static int getSreenSize(Activity activity, int flag) {
		int sreenSize = 0;
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		switch (flag) {
		case WINDOW_WIDTH:
			sreenSize = dm.widthPixels;
			break;
		case WINDOW_HEIGHT:
			sreenSize = dm.heightPixels;
			break;
		}
		return sreenSize;
	}

	/**
	 * 
	 * @author qiwx
	 * @createdate 2014-8-7 下午4:45:21
	 * @Description:获取cpu信息
	 * @type
	 * @throws Exception
	 */
	// 获取Cpu信息
	public static String[] getCpuInfo() {
		String str1 = "/proc/cpuinfo";
		String str2 = "";
		String[] cpuInfo = { "", "" };
		String[] arrayOfString;
		try {
			FileReader fr = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			for (int i = 2; i < arrayOfString.length; i++) {
				cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
			}
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			cpuInfo[1] += arrayOfString[2];
			localBufferedReader.close();
		} catch (IOException e) {
		}
		// tvHardwareInfo.append("CPU型号 " + cpuInfo[0] + "\n" + "CPU频率: " +
		// cpuInfo[1] + "\n");
		return cpuInfo;

	}

}
